package com.cykj.user.controller;
import com.cykj.system.api.RemoteFileService;
import com.cykj.common.core.domain.R;
import com.cykj.common.core.utils.StringUtils;
import com.cykj.common.core.utils.file.FileTypeUtils;
import com.cykj.common.core.utils.file.FileUtils;
import com.cykj.common.core.utils.file.MimeTypeUtils;
import com.cykj.system.api.domain.SysFile;
import com.cykj.user.domain.Customer;
import com.cykj.user.mapper.CustomerMapper;
import com.cykj.user.service.IUserInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Tag(name = "用户信息管理模块")
@RestController
@RequestMapping("/info")
public class UserInfoController {

    @Autowired
    CustomerMapper customerMapper;
    @Autowired
    private IUserInfoService userInfoService;

    @Resource
    private RemoteFileService remoteFileService;

    @Operation(summary = "获取用户信息")
    @GetMapping("/get")
    public R<Customer> getUserInfo(@RequestParam Integer id) { // 用id，类型Integer
        return userInfoService.getUserInfo(id);
    }

    @Operation(summary = "更新用户名")
    @PutMapping("/updateUsername")
    public R<String> updateUsername(
            @RequestBody Map<String, Object> params) {
        try {
            Integer userId = Integer.parseInt(params.get("userId").toString());
            String name = params.get("name").toString(); // 改为获取name参数
            return userInfoService.updateUsername(userId, name);
        } catch (Exception e) {
            return R.fail("参数格式错误");
        }
    }


    @Operation(summary = "删除用户")
    @DeleteMapping("/delete")
    public R<String> deleteUser(@RequestParam String userId) {
        return userInfoService.deleteUser(userId);
    }
    @Operation(summary = "上传头像")
    @PostMapping("/uploadAvatar")
    public R<Map<String, String>> uploadAvatar(@RequestParam("file") MultipartFile file,
                                               @RequestParam Integer id) {
        try {
            // 文件非空检查
            if (file.isEmpty()) {
                return R.fail("上传文件不能为空");
            }

            // 文件类型检查
            String extension = FileTypeUtils.getExtension(file);
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            String oldAvatarUrl = customerMapper.selectById(id).getAvatar();
            remoteFileService.delete(oldAvatarUrl);
            // 上传文件
            R<SysFile> fileResult = remoteFileService.upload(file);
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                return R.fail("文件服务异常，请联系管理员");
            }

            // 获取文件URL
            String url = fileResult.getData().getUrl();
            // 更新用户头像
            Customer customer = new Customer();
            customer.setId(id);
            customer.setAvatar(url);
            if (customerMapper.updateById(customer) > 0) {
                Map<String, String> result = new HashMap<>();
                result.put("url", url);
                return R.ok(result);
            }

            return R.fail("头像更新失败");
        } catch (Exception e) {
            return R.fail("上传图片异常，请联系管理员");
        }
    }

    @Operation(summary = "获取头像")
    @GetMapping("/getAvatar")
    public R<String> getAvatar(@RequestParam String userId) {
        Customer customer = customerMapper.selectById(userId);
        if (customer == null) {
            return R.fail("用户不存在");
        }
        return StringUtils.isNotEmpty(customer.getAvatar())
                ? R.ok(customer.getAvatar())
                : R.fail("用户未设置头像");
    }

    @Operation(summary = "更新余额")
    @PostMapping("/updateBalance")
    public R<String> updateBalance(@RequestBody Map<String, Object> params) {
        try {
            String userId = params.get("userId").toString();
            BigDecimal amount = new BigDecimal(params.get("amount").toString());
            return userInfoService.updateBalance(userId, amount);
        } catch (Exception e) {
            return R.fail("参数格式错误");
        }
    }
}
